﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using ProgramMain.Framework;
using ProgramMain.Properties;

namespace ProgramMain.PhoneTariffPlans
{
    public partial class PhoneTariffRateListCtl : BaseDetailCtl
    {
        private bool m_bDataInit = false;
        private bool m_bIsParent = false;

        public PhoneTariffRateListCtl()
        {
            InitializeComponent();

            this.gridView1.DoubleClick += new System.EventHandler(btnChangeCost_Click);
        }

        private Nullable<Int64> m_UniversalTariffPlanID;
        public Nullable<Int64> UniversalTariffPlanID
        {
            get { return m_UniversalTariffPlanID; }
            set
            {
                m_UniversalTariffPlanID = value;
            }
        }

        /// <summary>
        /// Событие, срабатывает на изменение фильтра по объекту
        /// </summary>
        public event EventHandler DetailIDEdited;

        protected virtual void OnDetailIDEdited(EventArgs e)
        {
            if (DetailIDEdited != null)
                DetailIDEdited(this, e);
        }

        protected override bool IsLoadDelayed()
        {
            return false;
        }

        public void ChangeTariffDetailsViewGrouping(bool bGroup)
        {
            if (bGroup)
                gridView1.GroupCount = 2;
            else
                gridView1.GroupCount = 0;
        }

        private void LoadHistoryData()
        {

            this.adapterPhoneTariffHistoryChanges.SelectCommandTimeout = Settings.Default.LongQueryTimeout;
            this.adapterPhoneTariffHistoryChanges.Fill(this.PhoneTariffDataSet.tblPhoneTariffHistoryChanges, DetailID);
            this.phoneTariffHistoryChanges.MoveFirst();
            if (this.phoneTariffHistoryChanges.Current != null)
            {
                DataRow CurrentRow = ((DataRowView)this.phoneTariffHistoryChanges.Current).Row;
                historyEdit.Text = CurrentRow["Description"].ToString();
            }
            else
            {
                historyEdit.Text = "";
            }
        }

        protected override void LoadData()
        {
            //прочитать данные из базы и заполнить датасет
            if (DetailID.HasValue && UniversalTariffPlanID.HasValue)
            {
                try
                {
                    m_bDataInit = true;

                    Nullable<bool> AllDateTypes;
                    Nullable<bool> IsParent;
                    this.adapterPhoneTariffRate.SelectCommandTimeout = Settings.Default.LongQueryTimeout;
                    this.adapterPhoneTariffRate.Fill(this.PhoneTariffDataSet.tblPhoneTariffRates, Convert.ToInt32(UniversalTariffPlanID.Value), DetailID, out AllDateTypes, out IsParent);

                    if (IsParent.HasValue)
                    {
                        m_bIsParent = IsParent.Value;
                    }
                    if (AllDateTypes.HasValue)
                    {
                        if (AllDateTypes.Value)
                        {
                            radioDateType.SelectedIndex = 1;
                        }
                        else
                        {
                            radioDateType.SelectedIndex = 0;
                        }
                    }
                    
                    LoadHistoryData();
                }
                finally
                {
                    m_bDataInit = false;
                }
            }
            else
            {
                this.PhoneTariffDataSet.tblPhoneTariffRates.Clear();
                this.PhoneTariffDataSet.tblPhoneTariffHistoryChanges.Clear();
                historyEdit.Text = "";
            }
        }

        protected override void UpdateData()
        {
            //update dataset
            this.adapterPhoneTariffRate.SetUpdateTimeout = Settings.Default.LongQueryTimeout;
            this.adapterPhoneTariffRate.Update(this.PhoneTariffDataSet.tblPhoneTariffRates);

            LoadHistoryData();
        }

        private void PhoneTariffRateListCtl_EnableEditingChanged(object sender, EventArgs e)
        {
            panelEditControls.Visible = EnableEdit;
        }

        private bool ParentExclamation()
        {
            return !m_bIsParent
                || XtraMessageBox.Show("Изменения данного тарифа будут автоматически применены ко всем дочерним тарифам по направлениям. Продолжить?", "Предупреждение", MessageBoxButtons.YesNo) == DialogResult.Yes;
        }

        private void radioDateType_EditValueChanged(object sender, EventArgs e)
        {
            if (!EnableEdit)
                return;

            try
            {
                if (!m_bDataInit)
                {
                    if (ParentExclamation())
                    {
                        try
                        {
                            ShowWaiting();
                            this.queriesTableAdapter.QueryCommandTimeout = Settings.Default.LongQueryTimeout;
                            if (UniversalTariffPlanID.HasValue)
                                this.queriesTableAdapter.qryPhoneTariffDetails_ChangeDateType(Convert.ToInt32(UniversalTariffPlanID.Value), DetailID, radioDateType.SelectedIndex == 1);

                            LoadData();
                        }
                        finally
                        {
                            HideWaiting();
                        }

                        OnDetailIDEdited(e);
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message, "Непредвиденная ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnAddTimeRange_Click(object sender, EventArgs e)
        {
            if (!EnableEdit)
                return;

            try
            {
                if (gridView1.IsGroupRow(gridView1.FocusedRowHandle)
                    && this.phoneTariffRateDataSource.Current != null
                    && this.controlTimeRange.Value.Minimum < this.controlTimeRange.Value.Maximum)
                {
                    if (ParentExclamation())
                    {
                        DataRow row = gridView1.GetDataRow(gridView1.FocusedRowHandle);
                        Int64 CurrentID = (Int64)row["ID"];

                        try
                        {
                            ShowWaiting();
                            
                            this.queriesTableAdapter.QueryCommandTimeout = Settings.Default.LongQueryTimeout;
                            if (UniversalTariffPlanID.HasValue)
                                this.queriesTableAdapter.qryPhoneTariffDetails_AddTimeRange(Convert.ToInt32(UniversalTariffPlanID.Value), DetailID.Value, CurrentID, controlTimeRange.Value.Minimum, controlTimeRange.Value.Maximum);

                            LoadData();
                        }
                        finally
                        {
                            HideWaiting();
                        }

                        OnDetailIDEdited(e);
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message, "Непредвиденная ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnDeleteTimeRange_Click(object sender, EventArgs e)
        {
            if (!EnableEdit)
                return;

            try
            {
                if (gridView1.IsGroupRow(gridView1.FocusedRowHandle)
                    && this.phoneTariffRateDataSource.Current != null)
                {
                    if (ParentExclamation())
                    {
                        DataRow row = gridView1.GetDataRow(gridView1.FocusedRowHandle);
                        Int64 CurrentID = (Int64)row["ID"];

                        try
                        {
                            ShowWaiting();
                            
                            this.queriesTableAdapter.QueryCommandTimeout = Settings.Default.LongQueryTimeout;
                            if (UniversalTariffPlanID.HasValue)
                                this.queriesTableAdapter.qryPhoneTariffDetails_DropTimeRange(Convert.ToInt32(UniversalTariffPlanID.Value), DetailID.Value, CurrentID);

                            LoadData();
                        }
                        finally
                        {
                            HideWaiting();
                        }

                        OnDetailIDEdited(e);
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message, "Непредвиденная ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnAddTrafficRange_Click(object sender, EventArgs e)
        {
            if (!EnableEdit)
                return;

            try
            {
                if (gridView1.IsGroupRow(gridView1.FocusedRowHandle)
                    && this.phoneTariffRateDataSource.Current != null
                    && this.editTrafficRangeFrom.Value < this.editTrafficRangeTo.Value)
                {
                    if (ParentExclamation())
                    {
                        DataRow row = gridView1.GetDataRow(gridView1.FocusedRowHandle);
                        Int64 CurrentID = (Int64)row["ID"];

                        try
                        {
                            ShowWaiting();
                            
                            this.queriesTableAdapter.QueryCommandTimeout = Settings.Default.LongQueryTimeout;
                            if (UniversalTariffPlanID.HasValue)
                                this.queriesTableAdapter.qryPhoneTariffDetails_AddTrafficRange(Convert.ToInt32(UniversalTariffPlanID.Value), DetailID.Value, CurrentID, (int)this.editTrafficRangeFrom.Value, (int)this.editTrafficRangeTo.Value);

                            LoadData();
                        }
                        finally
                        {
                            HideWaiting();
                        }

                        OnDetailIDEdited(e);
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message, "Непредвиденная ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnDeleteTrafficRange_Click(object sender, EventArgs e)
        {
            if (!EnableEdit)
                return;
            try
            {
                if (!gridView1.IsGroupRow(gridView1.FocusedRowHandle)
                    && this.phoneTariffRateDataSource.Current != null)
                {
                    if (ParentExclamation())
                    {
                        DataRow row = gridView1.GetDataRow(gridView1.FocusedRowHandle);
                        Int64 CurrentID = (Int64)row["ID"];

                        try
                        {
                            ShowWaiting();
                            
                            this.queriesTableAdapter.QueryCommandTimeout = Settings.Default.LongQueryTimeout;
                            if (UniversalTariffPlanID.HasValue)
                                this.queriesTableAdapter.qryPhoneTariffDetails_DropTrafficRange(Convert.ToInt32(UniversalTariffPlanID.Value), DetailID.Value, CurrentID);

                            LoadData();
                        }
                        finally
                        {
                            HideWaiting();
                        }

                        OnDetailIDEdited(e);
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message, "Непредвиденная ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void gridView1_CustomColumnDisplayText(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDisplayTextEventArgs e)
        {
            if (gridView1.IsGroupRow(e.RowHandle))
            {
                DataRow row = gridView1.GetDataRow(e.RowHandle);
                if (e.Column.FieldName == "DateType")
                {
                    e.DisplayText = row["DateRange"].ToString();
                }
                else if (e.Column.FieldName == "StartTime")
                {
                    e.DisplayText = row["TimeRange"].ToString();
                }
            }
            else if (gridView1.IsDataRow(e.RowHandle))
            {
                DataRow row = gridView1.GetDataRow(e.RowHandle);
                if (e.Column.FieldName == "From")
                {
                    e.DisplayText = row["TrafficRange"].ToString();
                }
            }
        }

        private void rangeTrackBarControl1_EditValueChanged(object sender, EventArgs e)
        {
            labelTimeRange.Text = controlTimeRange.Value.Minimum + " - " + controlTimeRange.Value.Maximum;
        }

        private void PhoneTariffRateListCtl_DetailIDChanged(object sender, EventArgs e)
        {
            DBRead();
        }

        private void btnChangeCost_Click(object sender, EventArgs e)
        {
            if (!EnableEdit)
                return;

            if (gridView1.IsDataRow(gridView1.FocusedRowHandle)
                && this.phoneTariffRateDataSource.Current != null)
            {
                DataRowView CurrentRowView = (DataRowView)this.phoneTariffRateDataSource.Current;
                CurrentRowView.Row["PhoneTariffDirection_ID"] = DetailID.Value;

                PhoneTariffRateDetailCtl frm = new PhoneTariffRateDetailCtl();
                frm.phoneTariffRateDataSource = this.phoneTariffRateDataSource;
                DialogResult dRes = frm.ShowModal(CheckSecurityEditAction(false));

                if (dRes == DialogResult.OK)
                {
                    DBWrite();

                    OnDetailIDEdited(e);
                }
            }
        }
    }
}
